import React, {useEffect, useState} from 'react';
import BattleSystem, {UnitType, UNIT_TYPES} from '../systems/BattleSystem';
import SaveSystem, {SaveSlot} from '../services/SaveSystem';
import {View, Text, StyleSheet, Button} from 'react-native';
import UnitsDisplay from '../components/UnitsDisplay';
import {useGame} from '../contexts/GameContext';
import BluetoothConnector from '../components/BluetoothConnector';

const GameScreen = ({route}) => {
  const {state, dispatch} = useGame();
  const {faction} = route.params;

  useEffect(() => {
    // Initialize Bluetooth
    const onDeviceFound = async (device: any) => {
      console.log('Found device:', device.name);
      try {
        await BluetoothConnector.connectToDevice(device.id);
        const handler = BluetoothConnector.addMessageHandler(message => {
          if (message.type === 'game_state') {
            dispatch(message.payload);
          } else if (message.type === 'battle_result') {
            const {attacker, target, damage, targetDestroyed} = message.payload;
            let updatedUnits = [...state.units];

            if (targetDestroyed) {
              updatedUnits = updatedUnits.filter(u => u.id !== target);
            }

            dispatch({units: updatedUnits});

            const logMessage = `远程: ${attacker}攻击了${target}，造成${damage}点伤害`;
            setBattleLog(prev => [...prev, logMessage]);
          } else if (message.type === 'player_action') {
            console.log('Player action:', message.payload);
          }
        });

        return () => handler(); // Cleanup
      } catch (error) {
        console.error('Connection error:', error);
      }
    };

    BluetoothConnector.scanDevices(onDeviceFound);

    // Set initial resources based on faction
    const initialResources = {
      grain: faction.id === 'ming' ? 100 : 50,
      horses: faction.id === 'mongol' ? 100 : 50,
      gunpowder: faction.id === 'japan' ? 100 : 50,
      dragonVein: 0,
    };

    const initialState = {
      resources: initialResources,
      gamePhase: 'battle',
      currentPlayer: {
        id: 'local_player',
        name: '玩家1',
        faction: faction,
        isCommander: true,
      }
    };

    dispatch(initialState);
    BluetoothConnector.syncGameState(initialState);
  }, [faction]);

  const handleAction = async (action: string, payload: any) => {
    await BluetoothConnector.sendAction(action, payload);
  };

  const [showSaveMenu, setShowSaveMenu] = useState(false);
  const [saves, setSaves] = useState<SaveSlot[]>([]);

  const handleEndTurn = async () => {
    const newState = {
      ...state,
      resources: {
        grain: state.resources.grain + 10,
        horses: state.resources.horses + 5,
        gunpowder: state.resources.gunpowder + 5,
        dragonVein: state.resources.dragonVein + 1,
      }
    };

    dispatch(newState);

    // 自动存档
    try {
      await SaveSystem.saveGame(newState);
      const updatedSaves = await SaveSystem.listSaves();
      setSaves(updatedSaves);
    } catch (error) {
      console.error('Auto-save failed:', error);
    }
  };

  const loadSave = async (saveId: string) => {
    try {
      const saveData = await SaveSystem.loadGame(saveId);
      if (!saveData) {
        throw new Error('存档数据加载失败');
      }

      // 验证存档数据
      if (!saveData.currentPlayer || !saveData.units) {
        throw new Error('存档数据不完整');
      }

      dispatch({
        ...saveData,
        timestamp: Date.now(), // 更新加载时间
      });

      setShowSaveMenu(false);
      setBattleLog(prev => [
        ...prev,
        `已加载存档 ${new Date(saveData.timestamp).toLocaleString()}`,

      // 同步到蓝牙连接设备
      await BluetoothConnector.syncGameState(saveData);
    } catch (error) {
      console.error('加载存档失败:', error);
      setBattleLog(prev => [...prev, `加载存档失败: ${error.message}`]);
    }
  };

  useEffect(() => {
    // 初始化时加载存档列表
    const loadSaves = async () => {
      const savedGames = await SaveSystem.listSaves();
      setSaves(savedGames);
    };
    loadSaves();
  }, []);

  const [selectedUnit, setSelectedUnit] = useState<UnitType | null>(null);
  const [battleLog, setBattleLog] = useState<string[]>([]);
  const [selectedTarget, setSelectedTarget] = useState<string | null>(null);

  const handleAttack = async () => {
    if (!selectedUnit || !selectedTarget || !state.currentPlayer) {return;}

    const attacker = state.units.find(
      u => u.type === selectedUnit && u.owner === state.currentPlayer?.id,
    );
    const target = state.units.find(u => u.id === selectedTarget);

    if (!attacker || !target) {return;}

    const result = BattleSystem.calculateBattle(attacker, target);

    let updatedUnits = [...state.units];
    if (target.health <= 0) {
      updatedUnits = updatedUnits.filter(u => u.id !== target.id);
    }

    dispatch({
      units: updatedUnits,
    });

    const logMessage = `${state.currentPlayer.name}的${attacker.type}攻击了${target.owner}的${target.type}，造成${result.damage}点伤害`;
    setBattleLog([...battleLog, logMessage]);

    await handleAction('battle_action', {
      attacker: selectedUnit,
      target: selectedTarget,
      damage: result.damage,
      targetDestroyed: target.health <= 0,
    });

    setSelectedUnit(null);
    setSelectedTarget(null);
  };

  const produceUnit = (type: UnitType) => {
    const unit = BattleSystem.createUnit(type, faction);
    if (
      BattleSystem.canAffordUnit(unit, state.resources) &&
      state.currentPlayer
    ) {
      const newUnit = {
        id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        type: unit.type,
        attack: unit.attack,
        defense: unit.defense,
        health: unit.health,
        owner: state.currentPlayer.id,
      };

      dispatch({
        resources: {
          grain: state.resources.grain - unit.cost.grain,
          horses: state.resources.horses - (unit.cost.horses || 0),
          gunpowder: state.resources.gunpowder - (unit.cost.gunpowder || 0),
          dragonVein: state.resources.dragonVein,
        },
        units: [...state.units, newUnit],
      });

      handleAction('produce_unit', {
        unitType: type,
        unitData: newUnit,
      });

      setBattleLog([
        ...battleLog,
        `${state.currentPlayer.name} 生产了${type}单位`,
      ]);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>永乐雄心 - {faction.name}</Text>

      <View style={styles.resourceContainer}>
        <Text>漕粮: {state.resources.grain}</Text>
        <Text>战马: {state.resources.horses}</Text>
        <Text>硝石: {state.resources.gunpowder}</Text>
        <Text>龙脉: {state.resources.dragonVein}</Text>
      </View>

      <View style={styles.battleSection}>
        <Text style={styles.sectionTitle}>军事行动</Text>
        <View style={styles.unitButtons}>
          {Object.keys(UNIT_TYPES).map(type => (
            <Button
              key={type}
              title={`生产${type}`}
              onPress={() => produceUnit(type as UnitType)}
              color={selectedUnit === type ? '#4CAF50' : undefined}
            />
          ))}
        </View>

        {selectedUnit && (
          <View style={styles.selectionSection}>
            <Text>已选择: {selectedUnit}</Text>
            <Button
              title="取消选择"
              onPress={() => setSelectedUnit(null)}
              color="#F44336"
            />
          </View>
        )}

        {selectedUnit && !selectedTarget && (
          <View style={styles.targetSelection}>
            <Text>选择攻击目标:</Text>
            {state.units
              .filter(unit => unit.owner !== state.currentPlayer?.id)
              .map(unit => (
                <Button
                  key={unit.id}
                  title={`${unit.owner}的${unit.type}`}
                  onPress={() => setSelectedTarget(unit.id)}
                />
              ))}
          </View>
        )}

        {selectedTarget && (
          <View style={styles.confirmSection}>
            <Text>
              目标: {state.units.find(u => u.id === selectedTarget)?.type}
            </Text>
            <Button title="发动攻击" onPress={handleAttack} color="#F44336" />
            <Button
              title="取消"
              onPress={() => setSelectedTarget(null)}
            />
          </View>
        )}
      </View>

      <UnitsDisplay />

      <View style={styles.phaseContainer}>
        <Text>当前阶段: {state.gamePhase}</Text>
        <View style={styles.actionButtons}>
          <Button title="结束回合" onPress={handleEndTurn} />
          <Button
            title="存档"
            onPress={() => setShowSaveMenu(true)}
            color="#4CAF50"
          />
        </View>
      </View>

      {/* 存档菜单 */}
      {showSaveMenu && (
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>游戏存档</Text>

            <Button
              title="新建存档"
              onPress={async () => {
                await SaveSystem.saveGame(state);
                const updatedSaves = await SaveSystem.listSaves();
                setSaves(updatedSaves);
              }}
            />

            {saves.map(save => (
              <View key={save.id} style={styles.saveItem}>
                <Text>
                  {save.preview.faction} - 回合: {save.preview.turn}
                </Text>
                <Text>{new Date(save.timestamp).toLocaleString()}</Text>
                <View style={styles.saveActions}>
                  <Button
                    title="加载"
                    onPress={() => loadSave(save.id)}
                    color="#2196F3"
                  />
                  <Button
                    title="删除"
                    onPress={async () => {
                      await SaveSystem.deleteSave(save.id);
                      const updatedSaves = await SaveSystem.listSaves();
                      setSaves(updatedSaves);
                    }}
                    color="#F44336"
                  />
                </View>
              </View>
            ))}

            <Button
              title="关闭"
              onPress={() => setShowSaveMenu(false)}
            />
          </View>
        </View>
      )}

      <View style={styles.logContainer}>
        {battleLog.map((log, index) => (
          <Text key={index}>{log}</Text>
        ))}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  resourceContainer: {
    marginBottom: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  battleSection: {
    marginVertical: 20,
    padding: 10,
    borderWidth: 1,
    borderRadius: 5,
  },
  sectionTitle: {
    fontWeight: 'bold',
    marginBottom: 10,
  },
  unitButtons: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginBottom: 10,
  },
  selectionSection: {
    marginVertical: 10,
    padding: 10,
    backgroundColor: '#f5f5f5',
    borderRadius: 5,
  },
  targetSelection: {
    marginTop: 10,
    padding: 10,
    backgroundColor: '#f0f8ff',
    borderRadius: 5,
  },
  confirmSection: {
    marginTop: 10,
    padding: 10,
    backgroundColor: '#fff0f0',
    borderRadius: 5,
  },
  phaseContainer: {
    marginTop: 20,
  },
  actionButtons: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 10,
  },
  modalContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10,
    width: '80%',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 15,
    textAlign: 'center',
  },
  saveItem: {
    marginVertical: 10,
    padding: 10,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 5,
  },
  saveActions: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 5,
  },
  logContainer: {
    marginTop: 20,
    maxHeight: 100,
    borderTopWidth: 1,
    paddingTop: 10,
  }
});

export default GameScreen;
